<template>
  <div v-waterMarker class="container merak-card">
    <div class="header">
      <div class="title">{{ $t("staff_list.add_new_employees") }}</div>
      <MerakIcon size="20" pointer @click="emit('close', state.refresh)">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
          <path
            d="M19,6.41L17.59,5L12,10.59L6.41,5L5,6.41L10.59,12L5,17.59L6.41,19L12,13.41L17.59,19L19,17.59L13.41,12L19,6.41Z"
          />
        </svg>
      </MerakIcon>
    </div>
    <div class="content">
      <div class="merak-overflow-y">
        <el-form ref="formRef" labelPosition="top" :model="formValue" :rules="formRules">
          <div class="group">
            <div class="group-title">{{ $t("staff_list.personal_info") }}</div>
            <el-row :gutter="40">
              <template v-for="item in formItems.userItems">
                <el-col v-if="item.visible !== false" :span="6">
                  <MerakXFormItem
                    v-bind="item"
                    :queryOptions="field => queryOptions(field)"
                    :label="$t(`staff_list.${item.prop}`)"
                    v-model:value="formValue[item.prop]"
                    v-model:default="formValue[`${item.prop}_txt`]"
                    @change="handleFormItemChange"
                  />
                </el-col>
              </template>
            </el-row>
          </div>
          <div class="group">
            <div class="group-title">{{ $t("staff_list.newsletter_info") }}</div>
            <el-row :gutter="40">
              <template v-for="item in formItems.newsletterItems">
                <el-col v-if="item.visible !== false" :span="6">
                  <MerakXFormItem
                    v-bind="item"
                    :queryOptions="field => queryOptions(field)"
                    :label="$t(`staff_list.${item.prop}`)"
                    v-model:value="formValue[item.prop]"
                    v-model:default="formValue[`${item.prop}_txt`]"
                    @change="handleFormItemChange"
                  >
                    <template #custom_mobile>
                      <el-row>
                        <el-col :span="9">
                          <el-form-item prop="country_code">
                            <el-select
                              class="qf_select"
                              v-model="formValue.country_code"
                              @change="() => formRef?.validateField('mobile')"
                            >
                              <el-option v-for="option in state.countryCodeOptions" :value="option.value" :label="option.label" />
                            </el-select>
                          </el-form-item>
                        </el-col>
                        <el-col :span="1">
                          <div style="text-align: center">-</div>
                        </el-col>
                        <el-col :span="14">
                          <el-form-item prop="mobile">
                            <el-input v-number class="qf_input" autocomplete="new-password" v-model="formValue.mobile" />
                          </el-form-item>
                        </el-col>
                      </el-row>
                    </template>
                  </MerakXFormItem>
                </el-col>
              </template>
            </el-row>
          </div>
          <div v-if="formValue.nationality === 'china'" class="group">
            <div class="group-title">{{ $t("staff_list.education_info") }}</div>
            <el-row :gutter="40">
              <el-col v-for="item in formItems.educationItems" :span="6">
                <MerakXFormItem
                  v-bind="item"
                  :queryOptions="field => queryOptions(field)"
                  :label="$t(`staff_list.${item.prop}`)"
                  v-model:value="formValue[item.prop]"
                  v-model:default="formValue[`${item.prop}_txt`]"
                  @change="handleFormItemChange"
                />
              </el-col>
            </el-row>
          </div>
          <div class="group">
            <div class="group-title">{{ $t("staff_list.on_the_job_info") }}</div>
            <el-row :gutter="40">
              <template v-for="item in formItems.jobItems">
                <el-col v-if="item.visible !== false" :span="6">
                  <template v-if="item.prop === 'org_group'">
                    <MerakXFormItem v-bind="item" :label="$t(`staff_list.${item.prop}`)" v-model:value="org_group" />
                  </template>
                  <template v-else>
                    <MerakXFormItem
                      v-bind="item"
                      :queryOptions="field => queryOptions(field)"
                      :label="$t(`staff_list.${item.prop}`)"
                      v-model:value="formValue[item.prop]"
                      v-model:default="formValue[`${item.prop}_txt`]"
                      @change="handleFormItemChange"
                    />
                  </template>
                </el-col>
              </template>
            </el-row>
          </div>
          <div class="group">
            <div class="group-title">{{ $t("staff_list.contract_info") }}</div>
            <el-row :gutter="40">
              <template v-for="item in formItems.contractItems">
                <el-col v-if="item.visible !== false" :span="6">
                  <MerakXFormItem
                    v-bind="item"
                    :queryOptions="field => queryOptions(field)"
                    :label="$t(`staff_list.${item.prop}`)"
                    v-model:value="formValue[item.prop]"
                    v-model:default="formValue[`${item.prop}_txt`]"
                    @change="handleFormItemChange"
                  />
                </el-col>
              </template>
            </el-row>
          </div>
        </el-form>
      </div>
    </div>
    <div class="btns">
      <el-button type="primary" plain @click="handleSave()">{{ $t("merak.save_continue") }}</el-button>
      <el-button type="primary" @click="handleSave(true)">{{ $t("merak.save") }}</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { FormRules } from "element-plus";

import { getCurrentInstance, ref, reactive, computed, watch, onMounted } from "vue";

import useDateFormat from "@/hooks/useDateFormat";

import { ElMessage, ElButton, ElRow, ElCol, ElForm, ElFormItem, ElSelect, ElOption, ElInput } from "element-plus";

import MerakIcon from "@/components/MerakIcon/index.vue";
import MerakXFormItem, { MerakXFormItemOption, MerakXFormItemChangeParams } from "@/components/MerakXFormItem";

import {
  renderAge,
  renderTwelve,
  renderConstellation,
  userItems,
  newsletterItems,
  educationItems,
  jobItems,
  contractItems
} from "../formItems";

import { ResultEnum } from "@/enums/httpEnum";
import {
  TreeOptionType,
  getDictOptions,
  getOrgTreeOptions,
  getNewJobNo,
  checkDuplicate,
  addPersonnel
} from "@/api/modules/sysManage/personnel";

import { confirmWarningMsg } from "@/utils/messageUtils";

import dayjs from "dayjs";

// 国籍关联字段
const nationalityRelatedKeys = [
  "employee_name",
  "employee_alias",
  "nationality",
  "sex",
  "birthday",
  "mobile",
  "passport_no",
  "company_email",
  "job_no",
  "username",
  "password",
  "hiredate",
  "org_group",
  "office_location_id",
  "direct_superiors",
  "contract_type",
  "contract_company_id",
  "contract_period",
  "contract_status",
  "contract_start",
  "contract_end",
  "contract_date",
  // 自定义的
  "country_code",
  "org_company",
  "org_department",
  "org_title"
];

// 离职字段
const departKeys = ["left_date", "left_reason"];

// 签证字段
const visaKeys = ["visa_type", "visa_number", "visa_entity", "visa_expiration_date"];

const currentInstance = getCurrentInstance();

const props = defineProps<{
  nationOptions: MerakXFormItemOption[];
}>();

const emit = defineEmits<{
  close: [refresh: boolean];
}>();

const { format } = useDateFormat();

const formRef = ref<InstanceType<typeof ElForm>>();

const state = reactive<{
  refresh: boolean;
  idTypeOptions: MerakXFormItemOption[];
  countryCodeOptions: MerakXFormItemOption[];
  constellationOptions: MerakXFormItemOption[];
  orgTreeOptions: MerakXFormItemOption[];
}>({
  refresh: false,
  idTypeOptions: [],
  constellationOptions: [],
  countryCodeOptions: [],
  orgTreeOptions: []
});

const formValue = reactive<Record<string, any>>({
  nationality: "china",
  sex: 0,
  household_registration_type: 0,
  marriage: 0,
  fertility: 0
});

const formRules = reactive<FormRules>({
  employee_name: [
    {
      required: true,
      trigger: "change",
      validator: (rule, value, callback) => {
        let reg = /[\d~`!@#$%^&*()\-_=+[\]{}|;:'",<.>/?]+/g;
        if (!value) {
          callback(new Error(currentInstance?.proxy?.$t("staff_list.employee_name_valid")));
        } else if (reg.test(value)) {
          callback(new Error(currentInstance?.proxy?.$t("staff_list.employee_name_valid_limit")));
        } else {
          callback();
        }
      }
    }
  ],
  employee_alias: [
    {
      trigger: "change",
      validator: (rule, value, callback) => {
        const reg = /[~`!@#$%^&*()\-_=+[\]{}|;:'",<.>/?]+/g;
        if (reg.test(value)) {
          callback(new Error(currentInstance?.proxy?.$t("staff_list.employee_alias_valid_limit")));
        } else {
          callback();
        }
      }
    }
  ],
  file_no: [
    {
      trigger: "change",
      validator: (rule, value, callback) => {
        const reg = /^[\w\s]*$/;
        if (!!value && !reg.test(value)) {
          callback(new Error(currentInstance?.proxy?.$t("staff_list.file_no_valid")));
        } else {
          callback();
        }
      }
    }
  ],
  id_no: [
    {
      trigger: "change",
      validator: (rule, value, callback) => {
        let reg: RegExp = /^[1-9]\d{5}(18|19|20|21|22)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|[Xx])$/;
        if (!!value && !reg.test(value)) {
          callback(new Error(currentInstance?.proxy?.$t("staff_list.id_valid")));
        } else {
          callback();
        }
      }
    }
  ],
  passport_no: [
    {
      trigger: "change",
      validator: (rule, value, callback) => {
        let reg: RegExp = /^[A-Za-z0-9]+$/;
        if (!!value && !reg.test(value)) {
          callback(new Error(currentInstance?.proxy?.$t("staff_list.id_valid")));
        } else {
          callback();
        }
      }
    }
  ],
  country_code: [{ required: true, message: currentInstance?.proxy?.$t("staff_list.country_code_valid") }],
  mobile: [
    {
      trigger: "change",
      validator: (rule, value, callback) => {
        let reg: RegExp;
        switch (formValue.country_code) {
          case 86:
            reg = /^1\d{10}$/;
            break;
          // case 7:
          //   reg = /^\d{10}$/;
          //   break;
          // case 375:
          //   reg = /^\d{9}$/;
          //   break;
          // case 374:
          //   reg = /^\d{8}$/;
          //   break;
          default:
            reg = /^[1-9]\d*$/;
            break;
        }
        if (!value) {
          callback(new Error(currentInstance?.proxy?.$t("staff_list.mobile_valid")));
        } else if (reg.test(value)) {
          callback();
        } else {
          callback(new Error(currentInstance?.proxy?.$t("staff_list.mobile_valid_limit")));
        }
      }
    }
  ],
  phone_ext: [
    {
      trigger: "change",
      validator: (rule, value, callback) => {
        const reg = /^[1-9]\d*$/;
        if (!!value && !reg.test(value)) {
          callback(new Error(currentInstance?.proxy?.$t("staff_list.phone_valid")));
        } else {
          callback();
        }
      }
    }
  ],
  phone: [
    {
      trigger: "change",
      validator: (rule, value, callback) => {
        const reg = /^[1-9]\d*$/;
        if (!!value && !reg.test(value)) {
          callback(new Error(currentInstance?.proxy?.$t("staff_list.phone_valid")));
        } else {
          callback();
        }
      }
    }
  ],
  personal_email: [
    {
      trigger: "change",
      validator: (rule, value, callback) => {
        const reg =
          /^[A-Za-z0-9]+([-._][A-Za-z0-9]+)*@[A-Za-z0-9]+(-[A-Za-z0-9]+)*(\.[A-Za-z]{2,6}|[A-Za-z]{2,4}\.[A-Za-z]{2,3})$/;
        if (!!value && !reg.test(value)) {
          callback(new Error(currentInstance?.proxy?.$t("staff_list.email_valid")));
        }
        callback();
      }
    }
  ],
  company_email: [
    {
      trigger: "change",
      validator: (rule, value, callback) => {
        const reg =
          /^[A-Za-z0-9]+([-._][A-Za-z0-9]+)*@[A-Za-z0-9]+(-[A-Za-z0-9]+)*(\.[A-Za-z]{2,6}|[A-Za-z]{2,4}\.[A-Za-z]{2,3})$/;
        if (!!value && !reg.test(value)) {
          callback(new Error(currentInstance?.proxy?.$t("staff_list.email_valid")));
        }
        callback();
      }
    }
  ],
  job_no: [
    {
      required: true,
      trigger: "blur",
      validator: (rule, value, callback) => {
        const reg = /^[0-9]*$/;
        if (!value) {
          callback(new Error(currentInstance?.proxy?.$t("staff_list.job_no_valid")));
        } else if (reg.test(value)) {
          checkDuplicate({ field: "job_no", value }).then(({ code, message }) => {
            if (code == ResultEnum.SUCCESS) {
              callback();
            } else {
              callback(new Error(message as string));
            }
          });
        } else {
          callback(new Error(currentInstance?.proxy?.$t("staff_list.integer_valid")));
        }
      }
    }
  ],
  username: [
    {
      required: true,
      validator: (rule, value, callback) => {
        const reg = /^[\w\s]*$/;
        if (!value) {
          callback(new Error(currentInstance?.proxy?.$t("staff_list.username_valid")));
        } else if (reg.test(value)) {
          callback();
        } else {
          callback(new Error(currentInstance?.proxy?.$t("staff_list.username_valid_limit")));
        }
      }
    },
    {
      trigger: "blur",
      validator: (rule, value, callback) => {
        checkDuplicate({ field: "username", value }).then(({ code, message }) => {
          if (code == ResultEnum.SUCCESS) {
            callback();
          } else {
            callback(new Error(message as string));
          }
        });
      }
    }
  ],
  password: [
    {
      required: true,
      trigger: "change",
      validator: (rule, value, callback) => {
        const reg = /^[a-zA-Z]\w{5,17}$/;
        if (!value) {
          callback(new Error(currentInstance?.proxy?.$t("staff_list.password_valid")));
        } else if (reg.test(value)) {
          callback();
        } else {
          callback(new Error(currentInstance?.proxy?.$t("staff_list.password_valid_limit")));
        }
      }
    }
  ],
  contract_period: [
    {
      trigger: "change",
      validator: (rule, value, callback) => {
        const reg = /^\d+(\.\d{1,1})?$/;
        if (!!value) {
          if (reg.test(value)) {
            if (Math.floor(value) > 100) {
              callback(new Error(currentInstance?.proxy?.$t("staff_list.contract_period_valid_limit")));
            }
            callback();
          } else {
            callback(new Error(currentInstance?.proxy?.$t("staff_list.one_float_valid")));
          }
        }
        callback();
      }
    }
  ]
});

const formItems = computed(() => {
  const { nationOptions } = props;
  const { idTypeOptions, constellationOptions, orgTreeOptions } = state;
  return {
    userItems: [...userItems].map(item => {
      let visible = true;
      if (!nationalityRelatedKeys.includes(item.prop)) {
        visible = formValue.nationality === "china";
      }
      if (item.prop === "nationality") {
        return {
          ...item,
          visible,
          options: nationOptions
        };
      }
      if (item.prop === "id_type") {
        return {
          ...item,
          visible,
          options: idTypeOptions.filter(option =>
            formValue.nationality === "china" ? true : [0, 6].includes(option.value as number)
          )
        };
      }
      if (item.prop === "constellation") {
        return { ...item, visible, options: constellationOptions };
      }
      return { ...item, visible };
    }),
    newsletterItems: [...newsletterItems].map(item => {
      if (!nationalityRelatedKeys.includes(item.prop)) {
        const visible = formValue.nationality === "china";
        return { ...item, visible };
      }
      return { ...item };
    }),
    educationItems: [...educationItems].map(item => {
      if (!nationalityRelatedKeys.includes(item.prop)) {
        const visible = formValue.nationality === "china";
        return { ...item, visible };
      }
      return { ...item };
    }),
    jobItems: [...jobItems].map(item => {
      let visible = true;
      if (!nationalityRelatedKeys.includes(item.prop)) {
        visible = formValue.nationality === "china";
      }
      if (departKeys.includes(item.prop)) {
        visible = formValue.status === 0 || formValue.status === 3;
      }
      if (visaKeys.includes(item.prop)) {
        visible = formValue.nationality === "china" && formValue.office_location_id === 4;
      }
      if (item.prop === "job_no" && item.type === "input") {
        const props = { ...(item.props ?? {}) };
        props.readonly = true;
        return { ...item, visible, props };
      }
      if (item.prop === "org_group") {
        return { ...item, visible, options: orgTreeOptions };
      }
      return { ...item, visible };
    }),
    contractItems: [...contractItems].map(item => {
      if (["contract_period", "contract_end"].includes(item.prop)) {
        return { ...item, visible: formValue.contract_type !== 3 };
      }
      return { ...item };
    })
  };
});

const org_group = computed({
  get() {
    const values: string[] = [];
    const options = formItems.value.jobItems.find(item => item.prop === "org_group")?.options ?? [];
    const queryValue = (value: string, level: number, options: MerakXFormItemOption[]) => {
      for (let option of options) {
        const optionValues = (option.value as string).split("-");
        if (optionValues.length === level && optionValues[optionValues.length - 1] === value) {
          return option.value;
        } else if (!!option.children?.length && !!queryValue(value, level, option.children)) {
          return queryValue(value, level, option.children);
        }
      }
    };
    const companyValues = [...(formValue.org_company ?? [])].map(value => queryValue(value.toString(), 1, options)) as string[];
    const departmentValues = [...(formValue.org_department ?? [])].map(value =>
      queryValue(value.toString(), 2, options)
    ) as string[];
    const titleValues = [...(formValue.org_title ?? [])].map(value => queryValue(value.toString(), 3, options)) as string[];
    // 遍历公司id的集合
    for (let companyValue of companyValues) {
      // 判断部门id的集合中是否有存在该公司下的部门
      if (departmentValues.some(departmentValue => departmentValue.includes(`${companyValue}-`))) {
        // 遍历部门id的集合
        for (let departmentValue of departmentValues) {
          // 判断部门存在该公司下
          if (departmentValue.includes(`${companyValue}-`)) {
            // 判断岗位id的集合中是否有存在该部门下的岗位
            if (titleValues.some(titleValue => titleValue.includes(`${departmentValue}-`))) {
              // 遍历岗位id的集合
              for (let titleValue of titleValues) {
                // 判断岗位存在该部门下
                if (titleValue.includes(`${departmentValue}-`)) {
                  values.push(titleValue);
                }
              }
            } else {
              // 当部门存在该公司下并且岗位集合中不存在该部门的岗位
              values.push(departmentValue);
            }
          }
        }
      } else {
        // 当部门集合中不存在该公司的部门
        values.push(companyValue);
      }
    }
    return [...new Set(values)];
  },
  set(values) {
    const org_company: number[] = [];
    const org_department: number[] = [];
    const org_title: number[] = [];
    for (let value of values) {
      const [company, department, title] = value.split("-");
      if (!!company) {
        org_company.push(Number(company));
      }
      if (!!department) {
        org_department.push(Number(department));
      }
      if (!!title) {
        org_title.push(Number(title));
      }
    }
    formValue.org_company = org_company;
    formValue.org_department = org_department;
    formValue.org_title = org_title;
  }
});

const handleFormItemChange = (params: MerakXFormItemChangeParams) => {
  switch (params.type) {
    case "input":
      if (!!params.data) {
        formValue[params.prop] = params.data.trim();
      }
      if (params.prop === "contract_period" && !!formValue.contract_start) {
        formValue.contract_end = dayjs(formValue.contract_start)
          .add(365 * Number(params.data), "day")
          .format(format);
      }
      break;
    case "select":
      if (params.prop === "contract_type" && params.data.value === 3) {
        if (!!formValue.contract_start) {
          formValue.contract_end = dayjs(formValue.contract_start).add(100, "year").format(format);
        }
        delete formValue.contract_period;
      }
      break;
    case "datePicker":
      if (params.prop === "contract_start") {
        if (formValue.contract_type === 3) {
          formValue.contract_end = dayjs(params.data).add(100, "year").format(format);
        } else if (typeof formValue.contract_period === "number" || !!formValue.contract_period) {
          formValue.contract_end = dayjs(params.data)
            .add(365 * Number(formValue.contract_period), "day")
            .format(format);
        }
      }
      break;
    default:
      break;
  }
};

const handleSave = (leave: boolean = false) => {
  formRef.value
    ?.validate()
    .then(() => {
      confirmWarningMsg({
        msg: currentInstance?.proxy?.$t("staff_list.add_employee_warning") ?? "",
        callback: (status: string) => {
          if (status === "confirm") {
            const user: Record<string, any> = {};
            const contract: Record<string, any> = {};
            for (let key of Object.keys(formValue)) {
              if (key.includes("contract_")) {
                contract[key] = formValue[key];
              } else {
                user[key] = formValue[key];
              }
            }
            addPersonnel({ user, contract: !!Object.keys(contract).length ? [contract] : [] }).then(({ code, message }) => {
              if (code == ResultEnum.SUCCESS) {
                state.refresh = true;
                formRef.value?.resetFields();
                org_group.value = [];
                queryJobNo();
                ElMessage.success(currentInstance?.proxy?.$t("staff_list.add_employee_success"));
                if (leave) {
                  emit("close", state.refresh);
                }
              } else if (typeof message === "string") {
                ElMessage.error(message);
              } else {
                const msg = Object.values(message)?.[0];
                ElMessage.error(msg);
              }
            });
          }
        }
      });
    })
    .catch(err => {
      const first = Object.keys(err)?.[0];
      if (!!first) {
        formRef.value?.scrollToField(first);
      }
    });
};

const queryJobNo = () => {
  getNewJobNo().then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      formValue.job_no = data.job_no;
    }
  });
};

const queryOptions = async (key?: string, parent_id?: string | number) => {
  if (!key) return;
  return getDictOptions({ key, parent_id }).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      return [...data].map(item => ({ value: item.key, label: item.value }));
    }
    return;
  });
};

// 国籍选择联动
watch(
  () => formValue.nationality,
  () => {
    if (formValue.nationality === "china") {
      ["household_registration_type", "marriage", "fertility"].forEach(key => {
        if (!formValue[key] && typeof formValue[key] !== "number") {
          formValue[key] = 0;
        }
      });
    } else {
      Object.keys(formValue).forEach(key => {
        if (!nationalityRelatedKeys.includes(key) && !nationalityRelatedKeys.map(key => `${key}_txt`).includes(key)) {
          formValue[key] = undefined;
        }
      });
    }
  },
  { immediate: true }
);

// 签证联动
watch(
  [() => formValue.nationality, () => formValue.office_location_id],
  () => {
    if (formValue.nationality !== "china" || formValue.office_location_id !== 4) {
      Object.keys(formValue).forEach(key => {
        if (visaKeys.includes(key)) {
          formValue[key] = undefined;
        }
      });
    }
  },
  { immediate: true }
);

// 员工状态联动
watch(
  () => formValue.status,
  () => {
    Object.keys(formValue).forEach(key => {
      if (formValue.status !== 0 && formValue.status !== 3 && departKeys.includes(key)) {
        formValue[key] = undefined;
      }
    });
  }
);

// 生日联动
watch([() => formValue.birthday, () => formValue.nationality], () => {
  if (!formValue.birthday || formValue.nationality !== "china") return;
  formValue.age = renderAge(formValue.birthday);
  formValue.twelve = currentInstance?.proxy?.$t(`staff_list.${renderTwelve(formValue.birthday)}`);
  formValue.constellation = renderConstellation(formValue.birthday).key;
});

// 证件号码重新校验
watch(
  () => formValue.id_type,
  () => {
    formRef.value?.validateField("id_no");
  }
);

// 转正日期联动
watch([() => formValue.hiredate, () => formValue.probation], () => {
  if (!formValue.hiredate || typeof formValue.probation !== "number") return;
  formValue.confirmation_date = dayjs(formValue.hiredate).add(formValue.probation, "month").format(format);
});

// 司龄联动
watch([() => formValue.hiredate, () => formValue.nationality], () => {
  if (!formValue.hiredate || formValue.nationality !== "china") return;
  formValue.company_seniority = renderAge(formValue.hiredate);
});

// 工龄联动
// watch(
//   () => formValue.first_job_date,
//   () => {
//     if (!formValue.first_job_date) return;
//     formValue.seniority = renderAge(formValue.first_job_date);
//   }
// );

// 合同类型联动;
watch(
  () => formValue.contract_type,
  () => {
    if (formValue.contract_type === 3) {
      delete formValue.contract_period;
    }
  }
);

// 合同结束日期联动
watch([() => formValue.contract_period, () => formValue.contract_start], () => {
  if (!formValue.contract_period || !formValue.contract_start) return;
  formValue.contract_end = dayjs(formValue.contract_start)
    .add(365 * Number(formValue.contract_period), "day")
    .format(format);
});

onMounted(() => {
  queryJobNo();
  // queryOptions("id_type").then(data => {
  //   state.idTypeOptions = [...(data ?? [])];
  // });
  queryOptions("constellation").then(data => {
    state.constellationOptions = [...(data ?? [])];
  });
  queryOptions("country_code").then(data => {
    state.countryCodeOptions = [...(data ?? [])];
  });
  getOrgTreeOptions().then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      const generate = (list: TreeOptionType[], parentId?: string) => {
        const arr: MerakXFormItemOption[] = [];
        for (let item of list) {
          const payload: MerakXFormItemOption = {
            value: `${!!parentId ? parentId + "-" : ""}${item.key}`,
            label: item.value
          };
          if (!!item.sublevel?.length) {
            payload.children = generate(item.sublevel, payload.value as string);
          }
          arr.push(payload);
        }
        return arr;
      };
      state.orgTreeOptions = generate(data);
    }
  });
});
</script>

<style scoped lang="scss">
.container {
  position: absolute;
  display: flex;
  align-items: center;
  flex-direction: column;
  margin-left: 0 !important;
  z-index: 10;
  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    .title {
      font-size: 20px;
    }
  }
  .content {
    flex: auto;
    margin: 30px 0 var(--merak-padding);
    width: 100%;
    min-height: 0;
  }
  .group {
    & + .group {
      margin-top: var(--merak-padding);
    }
    &-title {
      font-size: 16px;
      margin-bottom: 30px;
    }
  }
}
</style>
